package com.omesoft.hksnore.me;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.user.LoginActivity;
import com.omesoft.hksnore.util.DataCleanManager;
import com.omesoft.hksnore.util.dao.FamilyIfc;
import com.omesoft.hksnore.util.dao.FamilyIfcImpl;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfc;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.entity.FamilyDTO;
import com.omesoft.hksnore.util.json.ReErrorCode;
import com.omesoft.hksnore.util.myactivity.BaseFragment;
import com.omesoft.hksnore.util.omeview.MyDialog;
import com.omesoft.hksnore.util.omeview.OvalHollowImageView;
import com.omesoft.hksnore.util.photo.DownPhotoUtil;
import com.omesoft.hksnore.util.photo.MyBitmapUtil;
import com.omesoft.hksnore.util.thread.MyThread;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;
import com.omesoft.hksnore.util.web.CheckNetwork;
import com.umeng.analytics.MobclickAgent;

/**
 * 我的界面
 *
 * @autor omesoft_lgc
 * <p>
 * create at 2017/2/16 15:29
 */
public class MeFragment extends BaseFragment implements OnClickListener {
    private String TAG = "MeFragment";

    private View mainView;
    private Context context;
    private Activity activity;
    private Button mLogout_btn;
    private LinearLayout mAbout_ll, mMyDevice_ll, mKnoewledge_ll,mHandbook_ll;
    private TextView mNickNane_tv;
    private OvalHollowImageView mHeadPictrue_iv;
    private Bitmap bitmap;
    int hehe = 0;
    private FamilyIfc ifc;
    private FamilyDTO family;
    private MendaleSleepAllIfc allIfc;
    private MendaleSleepAllIfcImpl allIfcImpl;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
        context = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.snore_fragment_me, container, false);
        return mainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initHandler();
        initView();
        initTitle();
        loadView();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private void initTitle() {
        MyTitlebarUtil.setStateHeight(getActivity(), mainView.findViewById(R.id.state_bar), R.string.snore_main_mine, mainView);


    }

    protected void initView() {
        allIfc = new MendaleSleepAllIfcImpl(context);
        mNickNane_tv = (TextView) mainView.findViewById(R.id.me_tv_nickname);
        mLogout_btn = (Button) mainView.findViewById(R.id.me_btn_logout);
        mLogout_btn.setOnClickListener(this);
        mAbout_ll = (LinearLayout) mainView.findViewById(R.id.me_ll_about);
        mAbout_ll.setOnClickListener(this);
        mMyDevice_ll = (LinearLayout) mainView.findViewById(R.id.me_ll_my_device);
        mMyDevice_ll.setOnClickListener(this);
        mKnoewledge_ll = (LinearLayout) mainView.findViewById(R.id.me_ll_knowledge);
        mKnoewledge_ll.setOnClickListener(this);
        mHeadPictrue_iv = (OvalHollowImageView) mainView.findViewById(R.id.me_iv_head_pictrue);
        mHeadPictrue_iv.setOnClickListener(this);
        mHandbook_ll = (LinearLayout) mainView.findViewById(R.id.me_ll_handbook);
        mHandbook_ll.setOnClickListener(this);
    }


    protected void loadView() {
        try {
            ifc = new FamilyIfcImpl(context);
            family = ifc.findAll().get(0);

        }catch (Exception e){
            e.printStackTrace();
        }
        if (family == null){
            return;
        }

        if (family.getName() != null){

            mNickNane_tv.setText(family.getName());
        }else {
            mNickNane_tv.setText(MySharedPreferencesUtil.getName(context));
        }
        if (family.getAvatar()!= null) {
            String fileName = null;
            fileName = family.getAvatar();
            String reName;
            String[] str = fileName.split("/");
            if (str.length == 1) {
                reName = fileName;

            } else {

                reName = str[str.length - 1];
            }

//            System.out.println("renmame.." + reName);
            if (reName ==null || reName.equals("")){
                return;
            }
            bitmap = MyBitmapUtil.getAvatarBitmap(context, reName);
            if (bitmap != null) {
                System.out.println("设置头像");
                mHeadPictrue_iv.setImageBitmap(bitmap);
            } else {
                if (CheckNetwork.checkNetwork(activity)) {
                    MyThread.startNewThread(new Runnable() {
                        @Override
                        public void run() {
                            bitmap = new DownPhotoUtil().downloadPhotoAva(MySharedPreferencesUtil.getMemberId(context), family.getAvatar());
                            if (bitmap == null) {
                                loadAva(family.getAvatar());
                            }
                        }
                    });


                }
            }
        }

    }

    public void loadAva(final String avater) {
        if (avater != null) {
            bitmap = new DownPhotoUtil().downloadPhotoAva(MySharedPreferencesUtil.getMemberId(context), avater);
            sendMsg(handler, ReErrorCode.ERRCODE_JSON_ASK_USER_PHOTO, null);
        } else {

        }

    }

    protected void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case ReErrorCode.ERRCODE_JSON_ASK_USER_PHOTO:
                        loadView();
                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.me_btn_logout:
                showLogoutDialog();
                break;
            case R.id.me_ll_about:
                jumpActivityNotFinish(context, AboutActivity.class);
                break;
            case R.id.me_iv_head_pictrue:
                if (bitmap != null) {
                    jumpActivityNotFinish(context, ProfileAvtivity.class, bitmap);
                } else {
                    jumpActivityNotFinish(context, ProfileAvtivity.class);
                }
                break;
            case R.id.me_ll_my_device:
                jumpActivityNotFinish(context, MyDeviceActivity.class);
                break;
            case R.id.me_ll_knowledge:
                jumpActivityNotFinish(context,KnowledgeActivity.class);
                break;
            case R.id.me_ll_handbook:
                jumpActivityNotFinish(context,HandbookActivity.class);
                break;

        }
    }


    private Dialog myDialog;

    private void showLogoutDialog() {//注销登录提示窗口
        MyDialog.Builder builder = new MyDialog.Builder(context);
        builder.setTitle(R.string.dialog_logout_title);
        builder.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.btn_sure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                MobclickAgent.onProfileSignOff();
//                allIfc.deleteAllByID(MySharedPreferencesUtil.getMemberId(context));
                DataCleanManager.cleanApplicationData(context);
                ifc.deleteByID(MySharedPreferencesUtil.getMemberId(context));
                MySharedPreferencesUtil.cleanSp(context);
                jumpActivity(context, LoginActivity.class);
                myDialog.dismiss();

            }
        });
//        builder.create().show();
        myDialog = builder.create();
        myDialog.show();
    }


    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
    }
}
